<template>
  <el-dialog :title="title" :visible.sync="dialogvisible" width="600px" append-to-body class="my-dialog"
             :close-on-click-modal="false" @close="cancel">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="项目名称" prop="name">{{ projectName }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!--          公司-->
          <el-form-item label="甲方" prop="type">
            <el-select
              :style="{width: '100%'}"
              v-model="customId"
              filterable
              remote
              disabled
              reserve-keyword
              placeholder="请输入甲方信息关键词"
              :remote-method="remoteMethod_user"
              :loading="loading_company">
              <el-option
                v-for="item in user_list"
                :key="item.id"
                :label="item.name || '未知'"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同总价">
            {{ contractData ? contractData.money : 0 }}元
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="已开发票" prop="type">
            {{ openMoney }}元
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="开票金额" prop="money">
            <el-input v-model="form.money" placeholder="请输入"/>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="24">-->
        <!--          <el-form-item label="票据">-->
        <!--            <image-upload v-model="form.file" :limit="1" :isShowTip="false"/>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col :span="24">
          <el-form-item label="开票备注">
            <el-input
              v-model="form.remark"
              type="textarea"
              maxlength="100"
              show-word-limit
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-row>
<!--      <detailLog :logList="logList" :userLog="userLog"></detailLog>-->
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm" size="small" plain>确 定</el-button>
      <el-button @click="cancel" size="small" plain>取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  getProject
} from "@/api/system/project";
import {listCustom, getCustom} from '@/api/system/custom.js'
import {listDept, getDept} from "@/api/system/dept";
import {mapGetters} from 'vuex'
import {addInvoice, updateInvoice} from '@/api/system/contract.js'
import detailLog from "@/views/approval/examine/detailLog";
import {listFlow} from '@/api/system/design.js'
import {deptTreeAll} from '@/api/system/user'

export default {
  name: "detail",
  dicts: ['sys_stagnation_type', 'sys_purchase_type', 'sys_post_nature', 'sys_deposit_type', 'sys_deposit_status', 'sys_post_pay_method', 'sys_post_status'],
  props: ['visible', 'param', 'contractData'],
  components: {detailLog},
  data() {
    return {
      // 弹出层标题
      title: "开发票",
      // 是否显示弹出层
      dialogvisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        postCode: undefined,
        postName: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        projectId: '', // 项目ID
        money: '', // 金额
        remark: '', // 备注
        flowId: 0, // 审核流程id
        examineLog: null, // 审核明细
      },
      // 表单校验
      rules: {
        money: [
          {required: true, message: "金额不能为空", trigger: "blur"}
        ],
      },
      props: {
        lazy: true,
        label: "name",
        value: "id",
        lazyLoad: this.lazyLoad,
      },
      cascaderData: [], // 地址值
      postList: [],
      activeNames: ['1'],
      loading_company: false,
      compay_list: [],
      loading_user: false,
      user_list: [],
      projectType: [], // 项目类型/类别
      jobList: [],
      projectName: '',
      customId: 0,
      openMoney: 0,
      logList: null,
      userLog: null,
      deptOptions: [],
      flowData: null,
      depetUser: [], // 用户本身的部门链
      flowline: null
    };
  },
  computed: {
    ...mapGetters([
      'deptId',
      'company_id'
    ]),
  },
  watch: {
    visible() {
      this.dialogvisible = this.visible
      this.reset()
      if (this.visible) {
        console.log('this.param:', this.param) // 项目信息
        if (this.param) {
          this.getDetail()
        }
        this.examineFlowFn()
      }
    }
  },
  created() {
  },
  methods: {
    // 用户审核流程信息 examineFlow
    examineFlowFn() {
      listFlow({
        type: 26,
        companyId: this.company_id
      }).then(res => {
        if (res.rows.length) {
          this.flowData = res.rows[0]
          this.getDeptTree()
        }
      })
    },
    getDeptTree() {
      deptTreeAll().then(response => {
        this.deptOptions = response.data;
        this.checkExamine(0)
      });
    },
    // 审批流程判断采集
    checkExamine(data) {
      console.log('时长：', data.data)
      let that = this
      // this.unit = data.unit // 请假方式 // 单位 1-天 2-半天 3-小时
      // this.userTime = data.data
      this.depetUser = this.getItem(this.deptOptions) // 用户部门线上下级
      let flow_ = JSON.parse(that.flowData.flow)
      let flowline = that.$flowCheckFn(flow_.children, this.depetUser, 0)
      console.log('flowline:', flowline)
      if (flowline) {
        this.examinLine = this.$deepCopy(flowline)
        this.checklistLine(0)
      }
    },
    checklistLine(index) {
      let that = this
      if(index<this.examinLine.length){
        // assignedType==> 人工审批 ASSIGN_USER 自动通过 AUTO_PASS
        // setApproval==>
        // 指定成员 ASSIGN_USER;
        // 发起人自己 SELF_SELECT;
        // 角色 ROLE;
        // 部门主管 DEPART_DIRECTOR 查询当前账号的组织主管
        // 发起人自选 OPTIONAL;直属主管 REPORTS_TO;
        // moreUserSign  会签所有审批人同意通过 AND；或签其中一人同意通过 OR
        let item = this.$deepCopy(this.examinLine[index])
        if (item.assignedType === 'ASSIGN_USER') {
          switch (item.setApproval) {
            case 'ASSIGN_USER':
              item.userData = item.assignedUser
              that.$set(this.examinLine, index, item)
              that.checklistLine(index + 1)
              break;
            case 'SELF_SELECT':
              break;
            case 'OPTIONAL':
              break;
            case 'ROLE':
              break;
            case 'REPORTS_TO':
              break;
            case 'DEPART_DIRECTOR':
              getDept(this.deptId).then(response => {
                item.userData = [{id: response.data.userId, name: response.data.leader}]
                that.$set(this.examinLine, index, item)
                that.checklistLine(index + 1)
              });
              break;
          }
        }else if(item.assignedType == 'CC'){
          item.userData = this.$deepCopy(item.assignedUser)
          that.$set(this.examinLine, index, item)
          that.checklistLine(index + 1)
        }
      }else{
        console.log('完成部署：', this.examinLine)
        this.flowline = this.$deepCopy(this.examinLine)
      }
    },
    getItem(data) {
      for (let i = 0; i < data.length; i++) {
        const oItem = data[i];
        if (oItem.id === 203) {
          return [oItem.id];
        } else {
          if (oItem.children && oItem.children.length) {
            const result = this.getItem(oItem.children);
            if (result) {
              return [oItem.id].concat(result);
            }
          }
        }
      }
    },
    /** 详情 */
    getDetail() {
      getProject(this.param.id).then(response => {
        this.projectName = response.data.detail.name
        this.customId = response.data.detail.customId
        this.getUserDetail()
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let data_ = JSON.parse(JSON.stringify(this.form))
          data_.projectId = this.param.id
          if (!data_.money) {
            this.$modal.msgError("开票金额不能为空");
            return
          }
          if (!this.$isNumeric(data_.money)) {
            this.$modal.msgError("开票金额值需为数字类型");
            return
          }
          let lastmoney = this.contractData.money - this.openMoney
          if (parseInt(lastmoney) < parseInt(data_.money)) {
            this.$modal.msgError("开票金额需小于剩余金额");
            return
          }
          // 提交的参数 examineLog
          // examineId 审核id
          // name 名称
          // content // 自定义
          // userIds  步骤审核人
          // isExamine  0-待审核1-通过2-驳回
          // type 1 全部用户审核，2 单个用户审核
          // isAuto 是否直接通过0否1是
          // style 1 审核 2 抄送
          let examinelog_ = []
          for (let item of this.flowline) {
            let userData_ = []
            if (item.userData) {
              for (let user of item.userData) {
                userData_.push(user.id)
              }
            }
            // if(item.assignedUser){
            //   for (let user of item.assignedUser) {
            //     userData_.push(user.id)
            //   }
            // }
            examinelog_.push({
              // item.assignedType
              examineId: 0, // 审核id
              name: item.exaName, // 名称
              content: '', //
              userIds: userData_.join(','), //  步骤审核人
              isExamine: 0, //  0-待审核1-通过2-驳回
              type: item.moreUserSign ? (item.moreUserSign == 'AND' ? 1 : 2) : 0, // 全部用户审核，1个用户审核
              isAuto: item.assignedType == 'AUTO_PASS' ? 1 : 0, // 是否直接通过0否1是
              style: item.assignedType == 'CC' ? 2 : 1, // 1 审核 2 抄送
            })
          }
          data_.flowId = this.flowData.id || 0
          data_.examineLog = examinelog_
          if (data_.id != undefined) {
            updateInvoice(data_).then(response => {
              this.$emit('getList')
              this.$modal.msgSuccess("修改成功");
              this.cancel();
            });
          } else {
            addInvoice(data_).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.cancel();
            });
          }
        }
      });
    },
    cancel() {
      this.$emit('getList')
      this.$emit('update:visible', false)
    },
    reset() {
      this.form = {
        projectId: '', // 项目ID
        money: '', // 金额
        remark: '', // 备注
        flowId: 0, // 审核流程id
        nowUser: null, // 当前审核人
        examineContent: null, // 审核内容
        examineLog: null, // 审核明细
      }
      this.resetForm("form");
    },
    // 查询客户信息
    remoteMethod_user(query) {
      this.loading_user = true
      let query_ = {
        pageNum: 1,
        pageSize: 10,
        name: query
      }
      listCustom(query_).then(response => {
        this.user_list = response.rows;
        this.loading_user = false
      });
    },
    // 客户详情
    getUserDetail() {
      getCustom(this.customId).then(res => {
        this.user_list = [{
          id: Number(res.data.id),
          name: res.data.name
        }]
      })
    },
    // 查询运营主体信息
    remoteMethod_company(query) {
      this.loading_cmpany = true
      let query_ = {
        pageNum: 1,
        pageSize: 10,
        deptName: query,
        type: 1 // 固定类型
      }
      listDept(query_).then(response => {
        this.compay_list = response.data;
        this.loading_cmpany = false
      });
    },
    // 公司详情
    getCompanyDetail() {
      getDept(this.form.companyId).then(res => {
        this.compay_list = [{
          deptId: res.data.deptId,
          deptName: res.data.deptName
        }]
      })
    },
  }
}
</script>

<style scoped>

</style>
